<?php
/**
 * Class Same
 * Desc  不常用控制器
 * Create on 2021/8/3 14:58
 * Create by wangyafang
 */

namespace app\api\controller\xyb;


use addons\xyb\library\Wxapp;
use addons\xyb\XypHelper;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\api\model\xyb\UserPlat;
use app\api\model\xyb\UserWechat;
use app\api\service\UsersService;
use app\common\library\Token;
use app\common\model\xyb\AdminBelong;
use app\common\model\xyb\UserBelong;
use EasyWeChat\Factory;
use fast\Random;
use think\Config;
use app\api\model\xyb\UserAddress;
use app\api\model\xyb\UserReceiveApply;
use app\api\model\xyb\UserReceive;
use app\api\model\xyb\Order;
use app\common\model\circle\User as CircleUser;
use app\common\model\Circle;
use think\Db;

class User extends Base
{
// 无需登录的接口,*表示全部
    protected $noNeedLogin = ['third','is_register','baseInfo','get_phone','login','register'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    private $model;

    public function _initialize(){
        parent::_initialize();
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
        $this->model = new \app\common\model\User();
    }

    public function baseInfo(){
        // $users = $this->auth->getUser();
        $users = $this->getAuthUsers();
        $user_circle = UsersService::getUserCircleInfo($users->id);
        self::automaticRegister($users, $user_circle);

        /*用户信息*/
        $userPlatModel = new UserPlat();
        $where = ['user_id' => array('eq', $users->id)];
        $userPlatObj = $userPlatModel->where($where)->where('wechat_id', 'not null')->find();
        $min_run_fee = $this->configObj->min_run_fee;
        $max_run_fee = $this->configObj->max_run_fee;
        $run_fee = $this->configObj->run_fee;
        $customer_mobile = $this->configObj->customer_mobile;
        $service_img = $this->configObj->service_img;
        $miniapp_title = $this->configObj->miniapp_title;
        $login_logo = $this->configObj->login_logo;
        $loading = $this->configObj->loading;
        $applet_record_number = $this->configObj->applet_record_number;
        $login_logo = $login_logo ? $login_logo : '/uploads/20220324/Fp75Fco6CLA3xKroInecGetsEIDY.png';
        $loading = $loading ? $loading : '/uploads/20220324/FlZcjR3_obTOibTiGtx_TKRaSg7P.gif';
        $domain = $this->request->domain();
        $data = [
            'mobile'=>$userPlatObj ? $userPlatObj['mobile'] : '',

            'qiniu_url'=>$domain,
            'background' => 'https://api.youdaike.com/static/daijia/bj.png',
            'run_fee' => XypHelper::xyb_return_array_data($run_fee),
            'min_run_fee' => $min_run_fee,
            'max_run_fee' => $max_run_fee,
            'miniapp_title'=>$miniapp_title,
            'share_img'=>XypHelper::xyb_full_url($this->configObj->share_img),
            'share_title'=>$this->configObj->share_title,
            'customer_mobile'=>$customer_mobile,
            'service_img'=>XypHelper::xyb_full_url($service_img),
            'login_logo'=>$login_logo,
            'loading'=>$loading,
            'notice_title' => $this->configObj->share_title,
            'applet_record_number' => $applet_record_number,
            'reward_min_fee' => 1,
            'reward_item' => [1,2,3,4,5,6,7],
        ];
        $data['order_min_amount'] = $this->configObj->order_min_amount;
        $this->success('请求成功',$data);
    }

    /**
     * Desc  微信小程序是否注册
     * Create on 2024/5/30 11:57
     * Create by @小趴菜
     */
    public function is_register()
    {
        if(!$this->request->isGet()) {
            $this->error('请求类型错误');
        }
        $this->success('请求成功！',['auth_status'=>1]);
        $code=$this->request->param('code');
        if(empty($code)){
            $this->error('code参数错误');
        }
        $data=$this->get_wechat_session($code);
        if(empty($data['openid'])){
            $this->error('小程序登录失败',$data);
        }
        $openid=$data['openid'];
        $userWechatObj = (new UserWechat())->where('openid',$openid)->find();

        $auth_status = !empty($userWechatObj) ? 1 : 0;
        $this->success('请求成功！',['auth_status'=>$auth_status]);
    }


    public function login()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $this->success('请求成功',$this->getAuthUsers());
    }


    /**
     * Desc  微信小程序注册
     * Create on 2024/4/25 11:00
     * Create by @小趴菜
     */
    public function register()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $code=$this->request->post('code');
        $param = $this->request->post();

        $result = $this->validate($param,'app\api\validate\xyb\AppletUserWechat.register');
        if(true !== $result){
            // 验证失败 输出错误信息
            $this->error($result);
        }

        if(empty($code)){
            $this->error('code参数错误');
        }
        $data=$this->get_wechat_session($code);
        if(empty($data['openid'])){
            $this->error('小程序注册失败',$data);
        }
        $openid=$data['openid'];
        $nickname_avatar_data = $this->get_nickname_avatar();
        $avatar = (isset($param['avatar']) && !empty($param['avatar'])) ? $param['avatar'] : $nickname_avatar_data['avatar'];
        $mobile = (isset($param['mobile']) && !empty($param['mobile'])) ? $param['mobile'] : $nickname_avatar_data['mobile'];
        $nickname = (isset($param['nickname']) && !empty($param['nickname'])) ? $param['nickname'] : $nickname_avatar_data['nickname'];
        $result = \addons\xyb\library\Wxapp::checkSecurityText($openid,$nickname);
        if ($result != 1) {
            if ($result == 2) {
                $this->error('文本内容输入不合规，请重新输入');
            } else {
                $this->error('errcode:'.$result['errcode'].',errmsg:'.$result['errmsg']);
            }
        }
        Db::startTrans();
        try{
            $user= \app\common\model\User::create(array(
                'group_id'=>1,
                'status'=>'normal',
                'joinip'=>request()->ip(),
                'jointime'=>time(),
                'nickname'=>$nickname,
                'avatar'=>$avatar,
                'mobile'=>$mobile
            ),true);
            $UserWechat = UserWechat::create(array(
                'openid'=>$openid,
                'nickname'=>$nickname,
                'avatar'=>$avatar,
                'unionid' => isset($data['unionid']) ? $data['unionid'] : '',
                'session_key' => $data['session_key'],
                'createtime' => time(),
            ));
            UserBelong::create(array(
                'user_id' =>$user->id,
                'openid'=>$openid,
                'unionid' => isset($data['unionid']) ? $data['unionid'] : '',
                'session_key' => $data['session_key'],
                'xyb_group_id' => 1,
            ));
            UserPlat::create(array(
                'user_id' =>$user->id,
                'wechat_id' => $UserWechat->id,
                'mobile'=>$mobile,
                'createtime' => time(),
            ));
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->auth->direct($user->id);
        $userObj = $this->auth->getUserinfo();
        $userObj['avatar'] = XypHelper::xyb_full_url($userObj['avatar']);
        $this->success('请求成功',$userObj);
    }

    /**
     * Desc  微信小程序登录
     * Create on 2024/4/25 11:00
     * Create by @小趴菜
     */
    public function logincc()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $this->success('请求成功',$this->getAuthUsers());
        $code=$this->request->param('code');
        if(empty($code)){
            $this->error('code参数错误');
        }
        $data=$this->get_wechat_session($code);
        if(empty($data['openid'])){
            $this->error('小程序登录失败',$data);
        }
        $openid=$data['openid'];
        $userWechatObj = (new UserWechat())->where('openid',$openid)->find();
        $userPlatObj = (new UserPlat())->where('wechat_id',$userWechatObj['id'])->find();
        $userBelong = (new UserBelong())->where('openid',$openid)->find();
        $userObj = \app\common\model\User::get($userPlatObj['user_id']);
        if (!$userObj) {
            $userObj = \app\admin\model\User::create(array(
                'group_id'=>1,
                'status'=>'normal',
                'joinip'=>request()->ip(),
                'jointime'=>time(),
                'avatar'=> $userWechatObj['avatar'],
                'nickname'=> $userWechatObj['nickname'],
                'mobile'=> $userWechatObj['mobile'],
            ),true);
            $userPlatObj->user_id = $userObj->id;
            $userPlatObj->save();
            $userBelong->user_id = $userObj->id;
            $userBelong->save();
        }
        $this->auth->direct($userObj->id);
        $userObj = $this->auth->getUserinfo();
        $userObj['avatar'] = XypHelper::xyb_full_url($userObj['avatar']);
        $this->success('请求成功',$userObj);
    }

    /**
     * Desc  获取微信小程序用户手机号
     * Create on 2024/5/30 15:01
     * Create by @小趴菜
     */
    public function get_phone(){
        if(!$this->request->isGet()) {
            $this->error('请求类型错误');
        }
        $code=$this->request->get('code');
        $iv=$this->request->get('iv');
        $encryptedData=$this->request->get('encryptedData','','trim');
        if(empty($code)){
            $this->error('code 参数错误');
        }
        if(empty($iv)){
            $this->error('iv 参数错误');
        }
        if(empty($encryptedData)){
            $this->error('encryptedData 参数错误');
        }
        $data=Wxapp::phone($code,$iv,$encryptedData);
        $this->success('请求成功',$data);
    }

    private function get_nickname_avatar()
    {
        $avatar = '/assets/addons/xyb/img/default.png';

        $current_user_id = \app\common\model\User::where('id','desc')->limit(1)->value('id');
        if (!$current_user_id) {
            $current_user_id = 1;
        } else {
            $current_user_id = bcadd($current_user_id, 1);
        }
        $nickname = '用户'.$current_user_id;

        return array(
            'avatar'=>$avatar,
            'nickname'=>$nickname
        );
    }

    public function third()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $this->success('登录成功', ['token' => '6901f792-1c51-4525-b5aa-4364952c4754']);
        $code = $this->request->post("code");
        $wxResult = $this->get_wechat_session($code);
        $ck = UserBelong::where(['openid' => $wxResult['openid']])->find();
        if ($ck) {
            if(isset($wxResult['unionid']) && empty($ck['unionid'])) {
                $ck->unionid = $wxResult['unionid'];
            }
            $ck->session_key = $wxResult['session_key'];
            $ck->save();
            $this->_token = Random::uuid();
            Token::set($this->_token, $ck['user_id'], 2592000);
            $data = [
                'token'  => $this->_token,
            ];
            $this->success('登录成功', $data);
        } else {
            $this->success('请求成功');
        }
    }

    //获取微信openid和session_key
    public function get_wechat_session($code)
    {
        $config = [
            'app_id' => $this->configObj->app_id,
            'secret' => $this->configObj->app_secret,
            'response_type' => 'array',
        ];
        $app = Factory::miniProgram($config);

        return $app->auth->session($code);
    }


    public function user_address_list(){
        $userAddressModel = new UserAddress();
        $where = [
            'user_id'=>array('eq',$this->auth->id),
        ];
        $user_address_list = $userAddressModel->where($where)
            ->field('id,group_name,detail,name,mobile,defaults')
            ->order('id desc')
            ->select();
        foreach ($user_address_list as $k=>$v) {
            if($v['defaults'] == 1) {
                $user_address_list[$k]['defaults'] = true;
            } else {
                $user_address_list[$k]['defaults'] = false;
            }
        }
        $this->success('请求成功',$user_address_list);
    }

    public function auth()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $appPlat = $this->request->param('app_plat');
        $run_apply_status = (new UserReceiveApply())->where('agent_id',$this->request->param('agent_id'))->where('user_id',$this->auth->id)->where('app_plat',$appPlat)->value('status');
        if($run_apply_status == '') {
            $run_apply_status = 2;//没有申请过
        } else {
            $run_apply_status = (int)$run_apply_status;
        }
        $bind_agent_user_id = (new AdminBelong())->where('admin_id',$this->request->param('agent_id'))->where('bind_agent_user_id',$this->auth->id)->value('id');
        if(!$bind_agent_user_id) {
            $bind_agent_user_id = 0;
        }

        $param = $this->request->param();
        $userReceiveObj = (new UserReceive())->where([
            'agent_id'=>$param['agent_id'],
            'app_plat'=>$param['app_plat'],
            'user_id'=>$this->auth->id,
        ])->value('id');
        $auth = $userReceiveObj ? 1: 0;

        $user_info = array(
            'auth'=>$auth,
            'bind_agent_id'=>$bind_agent_user_id,
            'run_apply_status'=>$run_apply_status,
            'apply_receive_image_show'=>$this->configObj->apply_receive_image_show,
        );
        $this->success('请求成功',$user_info);
    }

    /**
     * desc:个人中心订单数量显示
     */
    public function center_order_count()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $param = $this->request->param();
        $orderModel = new Order();
        $this->success('请求成功',[
            'not_pay_count'=>$orderModel->where([
                'user_id'=>$this->auth->id,
                'agent_id'=>$param['agent_id'],
                'app_plat'=>$param['app_plat'],
                'status'=>0,
            ])->count(),
            'not_receive_count'=>$orderModel->where([
                'user_id'=>$this->auth->id,
                'agent_id'=>$param['agent_id'],
                'app_plat'=>$param['app_plat'],
                'status'=>1,
            ])->count(),
        ]);
    }

    public function update_default_agent_id()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $default_agent_id = $this->request->param('default_agent_id');
        $userBelong = new UserBelong();
        $userBelong->save([
            'default_agent_id'  => $default_agent_id,
        ],['user_id' => $this->auth->id]);
        $this->success('设置成功');
    }

    public function is_receiver(){
        $param = $this->request->param();
        $userReceiveObj = (new UserReceive())->where([
            'agent_id'=>$param['agent_id'],
            'app_plat'=>$param['app_plat'],
            'user_id'=>$this->auth->id,
        ])->value('id');
        $auth = $userReceiveObj ? 1: 0;
        $this->success('请求成功',['is_receiver'=>$auth]);
    }




}